/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Views;

import Classes.Materiel;
import Classes.Salle;
import DAO.DBConnect;
import DAO.MaterielDAO;
import DAO.SalleDAO;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.Map;
import java.util.Vector;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.table.DefaultTableModel;

/**
 *
 * @author Kévin
 */
public class vueImportList extends javax.swing.JFrame {

    JFileChooser chooser = new JFileChooser();
    private Map<Integer, Salle> listeSalle;
    private Map<Long, Materiel> mapMateriel;
    private LinkedList<String> codeBarreList;
    private LinkedList<Materiel> missingMateriel;
    private LinkedList<Materiel> extraMateriel;
    private LinkedList<Materiel> foundedMateriel;
    DefaultTableModel TabMaterielModel;
    private vueGlobale mainFrame;

    /**
     * Creates new form vueImportList
     */
    public vueImportList(JFrame mainFrame, Map<Integer, Classes.Salle> listeSalle) {
        initComponents();
        codeBarreList = new LinkedList<>();
        missingMateriel = new LinkedList<>();
        extraMateriel = new LinkedList<>();
        foundedMateriel = new LinkedList<>();
        mapMateriel = new HashMap<>();
        TabMaterielModel = (DefaultTableModel) TabMateriel.getModel();
        this.listeSalle = listeSalle;
        this.mainFrame = (vueGlobale)mainFrame;
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jButtonParcourir = new javax.swing.JButton();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        comboSalle = new javax.swing.JComboBox();
        jScrollPane1 = new javax.swing.JScrollPane();
        TabMateriel = new javax.swing.JTable();
        jButtonValider = new javax.swing.JButton();
        JB_Retour = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowClosed(java.awt.event.WindowEvent evt) {
                formWindowClosed(evt);
            }
            public void windowOpened(java.awt.event.WindowEvent evt) {
                formWindowOpened(evt);
            }
        });

        jButtonParcourir.setText("Parcourir");
        jButtonParcourir.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonParcourirActionPerformed(evt);
            }
        });

        jLabel1.setText("Séléctionnez le fichier à charger : ");

        jLabel2.setText("Importer un fichier");

        jLabel3.setText("Salle : ");

        comboSalle.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                comboSalleActionPerformed(evt);
            }
        });

        TabMateriel.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "N° de code barre", "Nom", "Descriptif", "Prix", "Salle"
            }
        ) {
            boolean[] canEdit = new boolean [] {
                false, false, false, false, false
            };

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        jScrollPane1.setViewportView(TabMateriel);
        TabMateriel.getColumnModel().getColumn(3).setPreferredWidth(15);
        TabMateriel.getColumnModel().getColumn(4).setPreferredWidth(15);

        jButtonValider.setText("Valider");
        jButtonValider.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonValiderActionPerformed(evt);
            }
        });

        JB_Retour.setText("Retour");
        JB_Retour.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                JB_RetourActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jScrollPane1)
                        .addContainerGap())
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, 472, Short.MAX_VALUE)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jLabel3)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(comboSalle, javax.swing.GroupLayout.PREFERRED_SIZE, 101, javax.swing.GroupLayout.PREFERRED_SIZE)))
                        .addGap(102, 102, 102)
                        .addComponent(jButtonParcourir)
                        .addGap(79, 79, 79))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addGap(0, 0, Short.MAX_VALUE)
                        .addComponent(jLabel2)
                        .addGap(265, 265, 265))))
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addGap(30, 30, 30)
                .addComponent(JB_Retour)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(jButtonValider)
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel2)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jLabel1)
                        .addGap(16, 16, 16)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel3)
                            .addComponent(comboSalle, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGap(18, 18, 18)
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jButtonValider)
                            .addComponent(JB_Retour)))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(16, 16, 16)
                        .addComponent(jButtonParcourir)))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    /**
     * Action du bouton parcourir (permet de récupérer un fichier depuis son poste)
     * @param evt 
     */
    private void jButtonParcourirActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonParcourirActionPerformed
        // TODO add your handling code here:
        int returnVal = chooser.showOpenDialog(jButtonParcourir);
        if (returnVal == JFileChooser.APPROVE_OPTION) {
            jLabel1.setText(chooser.getSelectedFile().getAbsolutePath());
        }
    }//GEN-LAST:event_jButtonParcourirActionPerformed

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
    }//GEN-LAST:event_jButton2ActionPerformed

    private void comboSalleActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_comboSalleActionPerformed
        
    }//GEN-LAST:event_comboSalleActionPerformed

    /**
     * Action s'éxécutant à l'ouverture de la fenêtre
     * @param evt 
     */
    private void formWindowOpened(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowOpened
        SalleDAO mySalleDAO = new SalleDAO(DBConnect.getInstance());

        for (Map.Entry<Integer, Salle> s : listeSalle.entrySet()) {
            comboSalle.addItem(s.getValue());
        }
    }//GEN-LAST:event_formWindowOpened

    /**
     * Action s'éxécutant après avoir cliquer sur le bouton valider (Chargement du fichier + traitement des informations)
     * @param evt 
     */
    private void jButtonValiderActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonValiderActionPerformed
        while (TabMaterielModel.getRowCount() != 0) {
            TabMaterielModel.removeRow(0);
        }
        missingMateriel.clear();
        extraMateriel.clear();
        foundedMateriel.clear();
        codeBarreList.clear();
        loadSalleMateriel();

        if (!chooser.getSelectedFile().getAbsolutePath().equalsIgnoreCase("")) {
            readFile(chooser.getSelectedFile().getAbsolutePath());
        }
        compare();
        loadTable();
    }//GEN-LAST:event_jButtonValiderActionPerformed

    /**
     * Bouton retour qui ferme la fenêtre en cours
     * @param evt 
     */
    private void BTN_BackActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_BTN_BackActionPerformed
       this.dispose();
    }//GEN-LAST:event_BTN_BackActionPerformed

    /**
     * Action qui récupère la fenêtre principale suite à la fermeture de la fenêtre d'importation
     * @param evt 
     */
    private void formWindowClosed(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosed
        this.mainFrame.setVisible(true);
    }//GEN-LAST:event_formWindowClosed

    private void JB_RetourActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_JB_RetourActionPerformed
        // TODO add your handling code here:
        this.dispose();
    }//GEN-LAST:event_JB_RetourActionPerformed

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton JB_Retour;
    private javax.swing.JTable TabMateriel;
    private javax.swing.JComboBox comboSalle;
    private javax.swing.JButton jButtonParcourir;
    private javax.swing.JButton jButtonValider;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JScrollPane jScrollPane1;
    // End of variables declaration//GEN-END:variables
/**
 * charge dans une linkedlist les différent code barre contenu dans le fichier d'inventaire
 * @param fichier (chemin du fichier à charger)
 */
    private void readFile(String fichier) {

        try {
            InputStream ips = new FileInputStream(fichier);
            InputStreamReader ipsr = new InputStreamReader(ips);
            BufferedReader br = new BufferedReader(ipsr);
            String ligne;

            while ((ligne = br.readLine()) != null) {

                codeBarreList.add(ligne);
                //   System.out.println(ligne);
            }

            br.close();
        } catch (Exception e) {
            System.out.println(e.toString());
        }
    }

    /**
     * Charge la map contenant tout les matériels d'une salle
     */
    private void loadSalleMateriel() {
        MaterielDAO myMaterielDAO = new MaterielDAO(DBConnect.getInstance());
        mapMateriel = myMaterielDAO.loadBySalle(((Salle) comboSalle.getSelectedItem()).getIdS());

    }

    /**
     * Compare le fichier d'inventaire avec les matériels présent en base pour
     * une salle donnée
     *
     * @author Valentin
     */
    private void compare() {
        Iterator i = codeBarreList.iterator();
        MaterielDAO myMaterielDAO = new MaterielDAO(DBConnect.getInstance());

        while (i.hasNext()) {
            Long numCB = Long.decode((String) i.next());

            // materiel présent en base et dans l'inventaire
            if (mapMateriel.containsKey(numCB)) {
                foundedMateriel.add(mapMateriel.get(numCB));
                mapMateriel.remove(numCB);
            } //materiel présent dans l'inventaire mais pas en base  
            else {
                Materiel myMateriel = new Materiel();
                myMateriel = myMaterielDAO.loadByCodeBarre(numCB);

                if (myMateriel.getNumCB() == 0) {
                    myMateriel.setNumCB(numCB);
                    myMateriel.setNom("<html><b>Inconnu en base</b>");
                }
                extraMateriel.add(myMateriel);
            }
        }
        // materiel présent en base mais pas dans l'inventaire
        for (Map.Entry<Long, Materiel> entry : mapMateriel.entrySet()) {
            missingMateriel.add(entry.getValue());
        }

    }

    /**
     * Charge le tableau inquiquant les matériels manquant, présent et en trop
     *en fonction du fichier d'inventaire et de la salle selectionnée
     * @author Valentin
     */
    private void loadTable() {
        String[] rowData = new String[1];

        // foundedMateriel
        rowData[0] = "<html><b style=\"font-size:11px\">Matériel trouvé:</b> ";
        TabMaterielModel.addRow(rowData);
        Iterator i = foundedMateriel.iterator();
        while (i.hasNext()) {
            Vector myVector = new Vector();
            Materiel myMateriel = new Materiel();
            myMateriel = (Materiel) i.next();
            myVector.add(myMateriel);
            myVector.add(myMateriel.getNom());
            myVector.add(myMateriel.getDescriptif());
            myVector.add(myMateriel.getPrixHT());
            myVector.add(listeSalle.get(myMateriel.getIdS()));
            TabMaterielModel.addRow(myVector);
        }

        // missingMateriel
        rowData[0] = "<html><b style=\"font-size:11px\">Matériel manquant :</b>";
        TabMaterielModel.addRow(rowData);
        Iterator i1 = missingMateriel.iterator();
        while (i1.hasNext()) {
            Materiel myMateriel = new Materiel();
            Vector myVector = new Vector();
            myMateriel = (Materiel) i1.next();
            myVector.add(myMateriel);
            myVector.add(myMateriel.getNom());
            myVector.add(myMateriel.getDescriptif());
            myVector.add(myMateriel.getPrixHT());
            myVector.add(listeSalle.get(myMateriel.getIdS()));
            TabMaterielModel.addRow(myVector);
        }

        // extraMateriel
        rowData[0] = "<html><b style=\"font-size:11px\">Matériel en trop : </b>";
        TabMaterielModel.addRow(rowData);
        Iterator i2 = extraMateriel.iterator();
        while (i2.hasNext()) {
            Materiel myMateriel = new Materiel();
            Vector myVector = new Vector();
            myMateriel = (Materiel) i2.next();
            myVector.add(myMateriel);
            myVector.add(myMateriel.getNom());
            myVector.add(myMateriel.getDescriptif());
            myVector.add(myMateriel.getPrixHT());
            myVector.add(listeSalle.get(myMateriel.getIdS()));
            TabMaterielModel.addRow(myVector);
        }

    }
}
